/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package spatialmarketplace.cem.dao.implementation;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import spatialmarketplace.cem.dao.DBHandler;
import spatialmarketplace.cem.dao.SMAdDao;
import spatialmarketplace.cem.model.SMAd;
import net.sourceforge.stripes.util.Log;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Implements the methods from the SMDao Interface to handle the database transactions regarding the SMAd
 * @author Camila
 */
    public class SMAdDaoImpl implements SMAdDao{
    private static final Log logger = Log.getInstance(ForumPostDaoImpl.class);
    private static SMAdDaoImpl instance = new SMAdDaoImpl();

    public static SMAdDaoImpl getInstance() {
        return instance;
    }

    @Override
    public ArrayList<SMAd> readAllAds() {
        DBHandler dbInstance = DBHandler.getInstance();
        ArrayList<SMAd> list = new ArrayList<SMAd>();
        SMAd ad;
        
        Integer adId; 
        String adTitle;
        String adImageLocation;
        String adLink;
        String adKeywords;

        try {
            if (dbInstance != null) {
                String query = new String("SELECT * FROM SM_Ad Limit 15");

                dbInstance.openConnection();
                ResultSet rs = dbInstance.executeQuery(query);

                try {
                    while (rs.next()) {
                        adId = Integer.valueOf(rs.getInt("adId"));
                        adTitle = rs.getString("adTitle");
                        adImageLocation = rs.getString("adImageLocation");
                        adLink = rs.getString("adLink");
                        adKeywords = rs.getString("adKeywords");

                        ad = new SMAd(adId, adTitle, adImageLocation, adLink, adKeywords);
                        list.add(ad);
                    }

                    dbInstance.closeConnection();

                } catch (SQLException ex) {
//                    ex.printStackTrace();
                    Logger.getLogger(DBHandler.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

        } catch (Exception e) {
//            e.printStackTrace();
            System.out.println("Error: " + e);
            logger.error("ERROR: " + ForumPostDaoImpl.class.getName() + ", " + e);
        }
        return list;
    }
    
}
